package com.itheima.web;

import com.itheima.pojo.User;
import com.itheima.service.UserService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    private UserService service = new UserService();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        User user = service.login(username, password);
        //获取复选框数据
        String remember = request.getParameter("remember");
        if(user != null){
            System.out.println("登录成功");
            //设置cookie
            if("1".equals(remember)){
                Cookie c_username = new Cookie("username",username);
                Cookie c_password = new Cookie("password",password);
                c_username.setMaxAge(604800);
                c_password.setMaxAge(604800);
                response.addCookie(c_username);
                response.addCookie(c_password);
            }else{
                Cookie[] cookies = request.getCookies();
                for (Cookie cookie : cookies) {
                    if("username".equals(cookie.getName()) || "password".equals(cookie.getName())){
                        Cookie cook = new Cookie(cookie.getName(),"");
                        cook.setMaxAge(0);
                        response.addCookie(cook);
                    }
                }
            }

            //跳转页面
            HttpSession session = request.getSession();
            session.setAttribute("user",user);
            response.sendRedirect(request.getContextPath() + "/selectAllServlet");
        }else {
            request.setAttribute("login_msg","用户名或密码错误");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
            System.out.println("登录失败");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
